import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Button, Input } from '@tarojs/components';
import ImageLoader from '../../components/ImageLoader';

import { uploadUserFile } from '../../contexts/store';
import { PageHeader } from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import { UserSubjectScore, UserScoreQrCode, FileItem, UserScoreVideoItem } from '../../types/myself';
import { getUserSubjectScoreApi, setUserSubjectScoreApi, deleteUserFileApi } from '../../api/myself';

import './index.scss';


const UserCarLicense: React.FC = () => {
  const firstLoad = useRef<boolean>(false);
  const { userInfo } = useAppContext();
  const userId = Number(userInfo?.id);
  const [price, setPrice] = useState<number>(0);
  const [hasEmpty, setHasEmpty] = useState<number>(0);
  const [qrode, setQrode] = useState<UserScoreQrCode[]>([]);
  const [priceName, setPriceName] = useState<string>("");
  const [scoreTotal, setScoreTotal] = useState<number>(0);
  const [exchangeNum, setExchangeNum] = useState<number>(0);
  const [fileList, setFileList] = useState<FileItem[]>([]);
  const [scoreList, setScoreList] = useState<UserSubjectScore[]>([]);
  const [fullScreenVisible, setFullScreenVisible] = useState(false);
  const [currentQrCode, setCurrentQrCode] = useState<UserScoreQrCode | null>(null);
  const [subjectList, setSubjectList] = useState<{name: string, id: number, score: number, status: number}[]>([
    {name: '科目一', id: 1, score: 0, status: 0},
    {name: '科目二', id: 2, score: 0, status: 0},
    {name: '科目三', id: 3, score: 0, status: 0},
    {name: '科目四', id: 4, score: 0, status: 0}
  ]);

  const getUserScore = async () => {
    try {
      const res = await getUserSubjectScoreApi();
      if (res.code === 200) {
        setScoreList(res.data.score);
        setSubjectList(subjectList.map((item) => {
          const score = res.data.score.filter((score: UserSubjectScore) => score.subject_id === item.id)?.[0];
          if (score) {
            item.score = score.score;
            item.status = res.data.status;
          }
          return item;
        }));
        setHasEmpty(res.data.status);
        setPrice(res.data.price.price);
        setPriceName(res.data.price.name);
        setScoreTotal(res.data.total);
        setExchangeNum(res.data.num);
        setFileList(res.data.video.map((item: UserScoreVideoItem) => ({
          uid: item.id.toString(),
          name: item.id.toString(),
          status: 'done',
          url: item.url || '',
          isSaved: true,
          percent: 100,
          thumbUrl: item.cover || '',
          cover: item.cover || ''
        })));
        setQrode(res.data.qrcode);
      } else {
        Taro.showToast({
          title: `获取考试成绩失败！${res.message}`,
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('获取成绩失败:', err);
      Taro.showToast({
        title: '获取考试成绩失败！',
        icon: 'none'
      });
    }
  };

  const handleFileUpload = async () => {
    try {
      await Taro.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: async(res) => {
        const uploadFile = res.tempFiles[0];
        let fileType = uploadFile.tempFilePath.split(".").pop() || 'mp4';
        await uploadUserFile(uploadFile.tempFilePath, 'video.'+fileType, "video/mp4", "score", userId).then(
          async(resp: any) => {
            if (resp.code === 200) {
              setFileList([
                ...fileList,
                {
                  uid: resp.data.uid,
                  name: resp.data.file_name,
                  percent: 100,
                  thumbUrl: resp.data.cover,
                  status: 'done',
                  url: resp.data.url,
                  isSaved: false,
                  cover: resp.data.cover,
                }
              ]);
              Taro.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              Taro.showToast({
                title: `上传失败:${resp.message}`,
                icon: 'none'
              });
            }
          }
        )}
      })
    } catch (err) {
      console.error('上传文件失败:', err);
      Taro.showToast({
        title: '上传文件失败！',
        icon: 'none'
      });
    }
  };

  // 自定义状态渲染
  const customStatusRender = (info: { status: string }) => {
    switch (info.status) {
      case 'expired':
        return (
          <View>
            <MaterialIcons name="cancel" color="red" size={16} />
            <Text> 已过期</Text>
          </View>
        );
      case 'scanned':
        return (
          <View>
            <MaterialIcons name="check_circle" color="green" size={16} />
            <Text> 已扫码</Text>
          </View>
        );
      case 'loading':
        return (
          <View>
            <MaterialIcons name="redo" color="green" size={16} />
            <Text> 已兑换</Text>
          </View>
        );
      default:
        return null;
    }
  };

  // 打开全屏模态框
  const openFullScreen = (item: UserScoreQrCode) => {
    if (item.status === 0) {
      setCurrentQrCode(item);
      setFullScreenVisible(true);
    }
  };

  // 关闭全屏模态框
  const closeFullScreen = () => {
    setFullScreenVisible(false);
    setCurrentQrCode(null);
  };

  const submitScore = async () => {
    let flag = false;
    const data: { [key: number]: number } = {};
    subjectList.forEach((item) => {
      data[item.id] = item.score;
      if (item.score === 0) {
        flag = true;
      }
    });
    if (flag || fileList.length === 0) {
      Taro.showToast({
        title: '请上传成绩录屏和四科成绩~',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await setUserSubjectScoreApi(data, fileList);
      if (res.code === 200) {
        Taro.showToast({
          title: '提交成功',
          icon: 'success'
        });
        setFileList(res.data.map((item: UserScoreVideoItem) => ({
          uid: item.id.toString(),
          name: item.id.toString(),
          status: 'done',
          url: item.url,
          isSaved: true,
          percent: 100,
          thumbUrl: item.cover,
          cover: item.cover
        })));
      } else {
        Taro.showToast({
          title: `提交失败：${res.message}`,
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('提交失败:', err);
      Taro.showToast({
        title: '提交失败',
        icon: 'none'
      });
    }
  };

  const viewVideo = (index: number, fileList: FileItem[]) => {
    console.log(982, index, fileList)
    Taro.previewMedia({
      sources: fileList.map((it) => ({
        url: it.url,
        type: 'video',
        poster: it.cover
      })),
      current: index,
    });
  };

  // 删除文件
  const deleteFile = async (item: FileItem) => {
    const file_id = item.isSaved ? item.uid : "";
    const url = item.isSaved ? "" : item.url;

    try {
      const res = await deleteUserFileApi(file_id, url);
      if (res.code === 200) {
        setFileList(fileList.filter((it) => it.uid !== item.uid));
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: `删除失败：${res.message}`,
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('删除失败:', err);
      Taro.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  };

  // 处理成绩变化
  const handleScoreChange = (id: number, value: string) => {
    const v = Number(value);
    if (isNaN(v)) {
      Taro.showToast({
        title: '请输入数字',
        icon: 'none'
      });
      return;
    }
    if (v < 0 || v > 100) {
      Taro.showToast({
        title: '请输入0-100的数字',
        icon: 'none'
      });
      return;
    }
    setSubjectList(subjectList.map(subject => 
      subject.id === id 
        ? { ...subject, score: v }
        : subject
    ));
  };

  const QRCode: React.FC<{value: string, size: number, status?: string, statusRender?: any}> = ({
    value, size, status, statusRender
  }) => {
    // 在小程序中，我们使用图片来模拟二维码
    return (
      <View className="user-car-license-qr-code-container" onClick={(e) => e.stopPropagation()}>
        <ImageLoader 
          src='200' 
          mode='aspectFit'
          style={{width: size, height: size}} 
        />
        {statusRender && status && statusRender({status})}
      </View>
    );
  };

  useEffect(() => {
    if (!firstLoad.current) {
      firstLoad.current = true;
      getUserScore();
    }
  }, []);

  return (
    <View className="user-car-license-page-container">
      {/* 顶部导航栏 */}
      <PageHeader title="上传考试合格成绩" />

      {/* 顶部标题区域 */}
      <View className="user-car-license-main-card">
        <View className="user-car-license-decorative-circle user-car-license-decorative-circle-yellow"></View>
        <View className="user-car-license-decorative-circle user-car-license-decorative-circle-green"></View>
        <Text className="user-car-license-main-title">我们拿证啦</Text>

        {/* 汽车插图 */}
        <View className="user-car-license-car-illustration">
          <View className="user-car-license-car-container">
            {/* 校车 */}
            <View className="user-car-license-car-body">
              <View className="user-car-license-car-light-left"></View>
              <View className="user-car-license-car-light-right"></View>
              <View className="user-car-license-car-window user-car-license-car-window-left"></View>
              <View className="user-car-license-car-window user-car-license-car-window-right"></View>
              <View className="user-car-license-car-window user-car-license-car-window-center">
                <View className="user-car-license-car-seat"></View>
                <View className="user-car-license-car-seat"></View>
              </View>
            </View>
            {/* 车轮 */}
            <View className="user-car-license-car-wheel user-car-license-car-wheel-left"></View>
            <View className="user-car-license-car-wheel user-car-license-car-wheel-right"></View>
            {/* 司机 */}
            <View className="user-car-license-car-person user-car-license-car-driver"></View>
            {/* 乘客 */}
            <View className="user-car-license-car-person user-car-license-car-passenger user-car-license-car-passenger-1"></View>
            <View className="user-car-license-car-person user-car-license-car-passenger user-car-license-car-passenger-2"></View>
            <View className="user-car-license-car-person user-car-license-car-passenger user-car-license-car-passenger-3"></View>
          </View>
        </View>

        {/* 四科满分区域 */}
        <View className="user-car-license-info-section">
          <Text className="user-car-license-section-title">四科满分</Text>
          <Text className="user-car-license-section-text">请上传 
            <Text className="user-car-license-highlight-text-red"> 交管12123APP </Text> 
            查分录屏可领取<Text className="user-car-license-highlight-text-red">666元</Text>平台奖励
            <Text className="user-car-license-highlight-text-orange">必须录屏，截图无效</Text>
          </Text>
        </View>

        {/* 填写成绩 */}
        <View className="user-car-license-info-section">
          <Text className="user-car-license-section-title">各科成绩</Text>
          <View className="user-car-license-subject-list">
            {subjectList.map((item, index) => (
              <View key={index}>
                <Text className="user-car-license-subject-title">
                  {item.name}
                </Text>
                <Input
                  type='number'
                  onInput={(e) => handleScoreChange(item.id, e.detail.value)}
                  disabled={item.status === 1}
                  value={item.score.toString()}
                  className='user-car-license-form-input'
                />
              </View>
            ))}
          </View>

          <View className="user-car-license-form-container">
            <View className="user-car-license-form-wrapper">
              {fileList.map((item, index) => (
                <View key={index} className="user-car-license-file-item">
                  <ImageLoader src={item.cover} mode='aspectFit' className="user-car-license-image" 
                   onClick={(e) => {
                      e.stopPropagation();
                      viewVideo(index, fileList);
                    }}
                  />
                  <View className='user-car-license-delete-badge' 
                    onClick={(e) => {
                      e.stopPropagation();
                      deleteFile(item);
                    }}
                  >
                    <MaterialIcons name="close" color="#ff4757" size={20} />
                  </View>
                </View>
              ))}
              {fileList.length >= 4 ? null : (
                <View 
                  className="user-car-license-file-upload"
                  onClick={handleFileUpload}
                >
                  <MaterialIcons name="add" color="#4F9CE0" size={24} />
                  <Text style={{ marginTop: 8 }}>上传录屏</Text>
                </View>
              )}
            </View>
          </View>
          {hasEmpty === 0 && (
            <Button type="primary" className="user-car-license-form-button" onClick={submitScore}>
              提交
            </Button>
          )}
        </View>
      </View>

      {/* 积分兑换区域 */}
      <View className="user-car-license-exchange-card">
        <View className="user-car-license-exchange-tag">
          积分兑换
        </View>
        <View className="user-car-license-subject-list">
          {subjectList.map((item, index) => (
            <View key={index} className="user-car-license-exchange-item">
              <Text className="user-car-license-exchange-item-name">{item.name}</Text>
              <Text className="user-car-license-exchange-item-score">{item.score}</Text>
              <Text className="user-car-license-exchange-item-time">
                {scoreList.filter((score) => score.subject_id === item.id)?.[0]?.update_time ? (
                  `更新时间：${scoreList.filter((score) => score.subject_id === item.id)?.[0]?.update_time}`
                ) : (
                  <></>
                )}
              </Text>
            </View>
          ))}
        </View>

        <View className="user-car-license-score-info-card">
          <Text className="user-car-license-score-info-text">您的四科共计得分
            <Text className="user-car-license-score-info-highlight">{scoreTotal}</Text>分，1分=1积分，
            可兑换<Text className="user-car-license-score-info-highlight">{scoreTotal}</Text>积分，1积分可以兑换<Text className="user-car-license-score-info-highlight">1</Text>元
            （兑换要求：转赠Ta人报名，Ta可抵扣现金）
         </Text>

          <Text className="user-car-license-score-info-text">
            您选择班型为：<Text className="user-car-license-price-info-highlight">{price}元 {priceName}</Text>，
          </Text>
          <Text className="user-car-license-score-info-text">
            一次可兑换<Text className="user-car-license-score-info-highlight">{scoreTotal}</Text>积分，
            可兑换<Text className="user-car-license-score-info-highlight">{exchangeNum}</Text>次，
            共计可以兑换<Text className="user-car-license-score-info-highlight">{scoreTotal * exchangeNum}</Text>元。
          </Text>

          <Text className="user-car-license-score-info-text">
            <Text className="user-car-license-exchange-warning">兑换要求：您在本平台上报名，学车拿证后，转赠Ta人报名，Ta可抵扣现金</Text>
          </Text>
          {qrode.length === 0 ? (
            <View>
              <Text>暂无二维码</Text>
            </View>
          ) : (
            <View>
              <Text className="user-car-license-qrcode-tip">请将二维码扫描后，在APP中兑换</Text>
            </View>
          )}
          <View className="user-car-license-qrcode-grid">
            {qrode.map((item, index) => (
              <View key={index} className="user-car-license-qrcode-item">
                <View className="user-car-license-qrcode-card">
                  {/* 二维码显示 */}
                  <QRCode 
                    value={item.code} 
                    size={128} 
                    status={item.status === 1 ? 'scanned' : item.status === 2 ? 'loading' : item.status === 0 ? 'active' : 'expired'} 
                    statusRender={customStatusRender} 
                  />
                  <Text className="user-car-license-qrcode-sn">SN编号：
                    <Text className='user-car-license-qrcode-sn-highlight'>{item.sn}</Text>
                  </Text>
                  <Text className="user-car-license-qrcode-time">创建时间：{item.update_time}</Text>
                </View>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* 温馨提示区域 */}
      <View className="user-car-license-warning-box">
        <Text className="user-car-license-warning-title">温馨提示：</Text>
        <Text className="user-car-license-warning-content">如果没有上传录屏，则每科默认<Text className="user-car-license-warning-highlight">90</Text>分</Text>
      </View>

      {/* 全屏二维码模态框 */}
      {fullScreenVisible && (
        <View className="user-car-license-fullscreen-modal">
          <View className="user-car-license-modal-content">
            <View className="user-car-license-modal-header">
              <Text className="user-car-license-modal-title">兑换二维码</Text>
              <Button size="mini" onClick={closeFullScreen}>关闭</Button>
            </View>
            <View className="user-car-license-modal-body">
              {currentQrCode && (
                <>
                  {/* 二维码显示 */}
                  <QRCode 
                    value={currentQrCode.code} 
                    size={256} 
                    status={currentQrCode.status === 1 ? 'scanned' : currentQrCode.status === 2 ? 'loading' : currentQrCode.status === 0 ? 'active' : 'expired'} 
                    statusRender={customStatusRender} 
                  />
                  <Text className="user-car-license-modal-qrcode-info">SN: {currentQrCode.sn}</Text>
                  <Text className="user-car-license-modal-qrcode-time">创建时间：{currentQrCode.update_time}</Text>
                </>
              )}
            </View>
          </View>
        </View>
      )}
    </View>
  );
};

export default UserCarLicense;